package pro4;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.nio.file.*;
import java.util.UUID;

@WebServlet("/ProductUploadServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
        maxFileSize = 1024 * 1024 * 10,      // 10 MB
        maxRequestSize = 1024 * 1024 * 100   // 100 MB
)
public class ProductUploadServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取应用根目录
        String appPath = request.getServletContext().getRealPath("");
        // 构建上传目录路径
        String uploadPath = appPath + File.separator + UPLOAD_DIR;

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // 获取表单数据
            String productId = request.getParameter("productId");
            String productName = request.getParameter("productName");
            String price = request.getParameter("price");
            String description = request.getParameter("description");

            // 处理文件上传
            Part filePart = request.getPart("image");
            String fileName = filePart.getSubmittedFileName();

            // 生成唯一文件名
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

            // 保存文件
            String filePath = uploadPath + File.separator + uniqueFileName;
            try (InputStream fileContent = filePart.getInputStream()) {
                Files.copy(fileContent, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            }

            // 构建可访问的图片URL
            String imageUrl = request.getContextPath() + "/Ans4/uploads/" + uniqueFileName;

            // 在这里可以将商品信息保存到数据库
            // ...

            // 设置成功消息
            request.setAttribute("message", "商品添加成功！");
            request.setAttribute("imageUrl", imageUrl);

        } catch (Exception e) {
            request.setAttribute("message", "商品添加失败: " + e.getMessage());
        }

        // 转发回商品管理页面
        request.getRequestDispatcher("product_management.jsp").forward(request, response);
    }
}